package com.ruoyi.project.tool.swagger;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.OperatorType;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysType;
import com.ruoyi.project.system.es.SysDeptRepository;
import com.ruoyi.project.system.es.SysTypeRepository;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api("店铺信息管理")
@RestController
@RequestMapping("/mobile")
public class ShopController {
    @Autowired
    SysDeptRepository sysDeptRepository;

    @Autowired
    SysTypeRepository sysTypeRepository;

    @RequestMapping(value = "/restaurants", method = RequestMethod.GET)
    @Log(title = "店铺列表", operatorType = OperatorType.MOBILE)
    public AjaxResult listShop(@RequestParam(value = "latitude", required = false) Double lat,
                               @RequestParam(value = "longitude", required = false) Double lng,
                               @RequestParam(value="name",required = false) String name,
                               @RequestParam(value="offset",required = false) String offset,
                               @RequestParam(value="deliveryMode",required = false) String deliveryMode,
                               @RequestParam(value = "restaurant_category_ids",required = false) Long[] categoryIds,
                               @RequestParam(value = "supportIds",required = false) Long[] attrIds) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder=new NativeSearchQueryBuilder();
        BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
        /**
         * 配送方式
         */
        if(!StringUtils.isEmpty(deliveryMode)){
            nestedBoolQueryBuilder.must(QueryBuilders.termQuery("delivery",deliveryMode));
        }
        /**
         *关键字
         */
        if(!StringUtils.isEmpty(name)){
            nestedBoolQueryBuilder.must(QueryBuilders.termQuery("deptName",name));
        }
        /**
         * 分类查询
         */
        if(null!=categoryIds&&categoryIds.length>0){
            nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("categoryData.categoryId", categoryIds));
        }
        /**
         *  属性查询
         */
        if(null!=attrIds&&attrIds.length>0){
            nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrData.attrId", attrIds));
        }
        /**
         * 距离查询
         */
        QueryBuilder distanceQueryBuilder = QueryBuilders.geoDistanceQuery("geo").point(lat,lng).distance("1000000000000", DistanceUnit.METERS);
        nestedBoolQueryBuilder.filter(distanceQueryBuilder);
        nativeSearchQueryBuilder.withFilter(nestedBoolQueryBuilder);
        NativeSearchQuery nativeSearchQuery=nativeSearchQueryBuilder.build();
        int pageSize=0;
        if(!"0".equals(offset)){
            pageSize=Integer.valueOf(offset)/10;
        }
        nativeSearchQuery.setPageable(new PageRequest(pageSize,10));
        Page<SysDept> page=sysDeptRepository.search(nativeSearchQuery);
        for(SysDept dept:page.getContent()){
            double distance = GeoDistance.ARC.calculate(lat, lng, dept.getGeo().getLat(),dept.getGeo().getLon(), DistanceUnit.METERS);
            dept.setDistance(distance+"");
            System.out.println(dept.getDeptName()+"+++"+distance);
        }
        return AjaxResult.success(page);
    }


    @RequestMapping(value = "/restaurants/search", method = RequestMethod.GET)
    @Log(title = "查询店铺列表", operatorType = OperatorType.MOBILE)
    public AjaxResult searchShop(@RequestParam(value = "latitude", required = false) Double lat,
                               @RequestParam(value = "longitude", required = false) Double lng,
                               @RequestParam(value="name",required = false) String name) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder=new NativeSearchQueryBuilder();
        BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
        /**
         *关键字
         */
        if(!StringUtils.isEmpty(name)){
            nestedBoolQueryBuilder.must(QueryBuilders.matchQuery("deptName",name));
        }
        /**
         * 距离查询
         */
        QueryBuilder distanceQueryBuilder = QueryBuilders.geoDistanceQuery("geo").point(lat,lng).distance("1000000000000", DistanceUnit.METERS);
        nestedBoolQueryBuilder.filter(distanceQueryBuilder);
        nativeSearchQueryBuilder.withFilter(nestedBoolQueryBuilder);
        NativeSearchQuery nativeSearchQuery=nativeSearchQueryBuilder.build();
        Page<SysDept> page=sysDeptRepository.search(nativeSearchQuery);
        for(SysDept dept:page.getContent()){
            double distance = GeoDistance.ARC.calculate(lat, lng, dept.getGeo().getLat(),dept.getGeo().getLon(), DistanceUnit.METERS);
            dept.setDistance(distance+"");
            System.out.println(dept.getDeptName()+"+++"+distance);
        }
        return AjaxResult.success(page.getContent());
    }


    @RequestMapping(value = "/restaurant/{id}", method = RequestMethod.GET)
    @Log(title = "店铺详情", operatorType = OperatorType.MOBILE)
    public AjaxResult getShop(@PathVariable("id") Integer id) {
        Optional<SysDept> list= sysDeptRepository.findById(id);
        SysDept sysDept=list.get();
        List<Map> activites=new ArrayList<>();
        Map map1=new HashMap();
        map1.put("iconColor","f07373");
        map1.put("iconName","减");
        map1.put("description","满50减20");
        activites.add(map1);
        Map map2=new HashMap();
        map2.put("iconColor","70bc46");
        map2.put("iconName","新");
        map2.put("description","新用户减10");
        activites.add(map2);
       sysDept.setActivities(activites);
        return AjaxResult.success(sysDept);
    }

    /**
     * 店铺分类查询
     * @param id
     * @return
     */

    @RequestMapping(value = "/type/{id}", method = RequestMethod.GET)
    @Log(title = "店铺商品分类", operatorType = OperatorType.MOBILE)
    public AjaxResult getShopType(@PathVariable("id") Integer id) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder=new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.termQuery("deptId",id));
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
        Iterable<SysType> list= sysTypeRepository.search(nativeSearchQueryBuilder.build());
        Iterator iterator=list.iterator();
        List<SysType> types=new ArrayList<>();
        while (iterator.hasNext()) {
            SysType sysType= (SysType) iterator.next();
            types.add(sysType);
        }
        return AjaxResult.success(types);
    }


}
